# -*- coding: utf-8 -*-

from __future__ import unicode_literals

from django.shortcuts import render,render_to_response
from django.template import loader,Context
from django.http import HttpResponse,HttpResponseRedirect
from people.models import BlogPost,test01,User,Article,apiurl
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from people.forms import UserForm
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import json,xlwt,StringIO
import django.core.serializers,django.db.models

def test(request):
    return render(request, 'bootstarp_test.html')

def api_url(request):
    api_list_data={}
    data = apiurl.objects.all()
    for a in data:
        api_list_data[a.name]=a.url
    resp = {'status': 200, 'result':0,'detail': 'Get success', 'message':api_list_data}
    my_response=HttpResponse(json.dumps(resp),content_type='application/json;charset=utf-8')
    my_response["Access-Control-Allow-Origin"] = "*"
    return my_response

@login_required(login_url="/login/")     
def api_action(request):
    if request.method == 'GET':
        data = apiurl.objects.all()[:15]
        context = {  
            'data': data,  
        }
        return render(request,'api_action.html',context)
    if request.method == 'POST':
        if request.POST['apiurl'] and request.POST['apiname']:
            apiurl.objects.create(name=request.POST['apiname'], url=request.POST['apiurl'])
        else:
            pass
        resp = {'status': 200, 'result':0,'detail': 'success', 'message':'get'}
        my_response=HttpResponse(json.dumps(resp),content_type='application/json;charset=utf-8')
        my_response["Access-Control-Allow-Origin"] = "*"
        return my_response
    else:
        pass
    
@login_required(login_url="/login/")     
def api_create(request):
    if request.method == 'GET':
        return render(request,'api_action.html')
    if request.method == 'POST':
        if request.POST['apiname']:
            data=apiurl.objects.create(name=request.POST['apiname'], url=request.POST['apiurl'])
        else:
            pass
        resp = {'status': 200, 'result':0,'detail': 'success', 'message':'ok'}
        my_response=HttpResponse(json.dumps(resp),content_type='application/json;charset=utf-8')
        my_response["Access-Control-Allow-Origin"] = "*"
        return my_response
    else:
        pass


@login_required(login_url="/login/")     
def api_delete(request):
    if request.method == 'GET':
        return render(request,'api_action.html')
    if request.method == 'POST':
        if request.POST['apiurl'] and request.POST['apiname']:      
            apiurl.objects.filter(name=request.POST['apiname'], url=request.POST['apiurl']).delete()
        else:
            pass
        resp = {'status': 200, 'result':0,'detail': 'success', 'message':'delete'}
        my_response=HttpResponse(json.dumps(resp),content_type='application/json;charset=utf-8')
        my_response["Access-Control-Allow-Origin"] = "*"
        return my_response
    else:
        pass

@login_required(login_url="/login/")     
def api_update(request):
    if request.method == 'GET':
        return render(request,'api_action.html')
    if request.method == 'POST':
        if request.POST['apiurl'] and request.POST['apiname']:      
            apiurl.objects.filter(name=request.POST['apiname']).update(name=request.POST['apiname'], url=request.POST['apiurl'])
        else:
            pass
        resp = {'status': 200, 'result':0,'detail': 'success', 'message':'delete'}
        my_response=HttpResponse(json.dumps(resp),content_type='application/json;charset=utf-8')
        my_response["Access-Control-Allow-Origin"] = "*"
        return my_response
    else:
        pass

def api_msg2(request):
    if request.method == 'POST':
        if 'searchname1' in request.POST:
            if request.POST['searchname1']:
                data = apiurl.objects.get_queryset().filter(django.db.models.Q(name__icontains=request.POST['searchname1'])|django.db.models.Q(url__icontains=request.POST['searchname1'])).order_by('id') 
                page = request.GET.get('page',1)
                paginator = Paginator(data, 8)
                age = request.GET.get('page',1)
                currentPage=int(page)
                try:
                    data = paginator.page(page)#获取当前页码的记录
                except PageNotAnInteger:
                    data = paginator.page(1)#如果用户输入的页码不是整数时,显示第1页的内容
                except EmptyPage:
                    data = paginator.page(paginator.num_pages)#如果用户输入的页数不在系统的页码列表中时,显示最后一页的内容                 
                context = {  
                    'data': data,  
                    }                             
            else:               
                message = "请输入内容"
            return render(request,'api_result.html',locals())
    else:
        data = apiurl.objects.get_queryset().order_by('id')
        paginator = Paginator(data, 8)
        page = request.GET.get('page',1)
        currentPage=int(page)
        try:
            data = paginator.page(page)#获取当前页码的记录
        except PageNotAnInteger:
            data = paginator.page(1)#如果用户输入的页码不是整数时,显示第1页的内容
        except EmptyPage:
            data = paginator.page(paginator.num_pages)#如果用户输入的页数不在系统的页码列表中时,显示最后一页的内容 
        context = {  
            'data': data,  
            }
        return render(request,'api_result.html',locals())

@login_required(login_url="/login/")     
def api_msg2_excel(request):
    excel_ldata = apiurl.objects.all().order_by('id')
    if request.method == 'GET':
        ws = xlwt.Workbook(encoding='utf-8')  
        w = ws.add_sheet(u"数据报表第一页")  
        w.write(0, 0, "id")  
        w.write(0, 1, u"内容")  
        w.write(0, 2, u"来源")
        excel_row=1
        for obj in excel_ldata:
            data_id = obj.id
            data_name = obj.name
            data_url = obj.url
            w.write(excel_row, 0, obj.id)  
            w.write(excel_row, 1, obj.name)  
            w.write(excel_row, 2, obj.url)  
            excel_row +=1
        sio = StringIO.StringIO()
        ws.save(sio)
        sio.seek(0)
        response = HttpResponse(sio.getvalue(),content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=apimessage_%s.xls' % "papapap"
        response.write(sio.getvalue()) 
        return response
    else:
        pass
        
def api_search_json(request):
    if request.method == 'GET':
#       data = apiurl.objects.values('name','url')
        search_name  = request.GET.get('search_name',None)
        data = apiurl.objects.values('name','url').filter(name=search_name)
    elif request.method == 'POST':
        try:
            req=json.loads(request.body)
            if req['search_name']:
                search_name  = req['search_name']
                data = apiurl.objects.values('name','url').filter(name=search_name)
            else:
                data = apiurl.objects.values('name','url')
        except Exception as e:
            data={'status': 400, 'result':1,'detail': 'json_error'}
            return HttpResponse(json.dumps(data,ensure_ascii=False), content_type="application/json")
    else:
        pass
    if data:   
        data=list(data)
#    resp = {'errorcode': 100, 'detail': '陈奕迅好耶'}
        return HttpResponse(json.dumps(data,ensure_ascii=False), content_type="application/json")
    else:
        data={'status': 400, 'result':1,'detail': 'value_error'}
        return HttpResponse(json.dumps(data,ensure_ascii=False), content_type="application/json")        